package com.main;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.weixin.service.WeixinService;
import org.apache.log4j.Logger;

import com.alipay.config.AlipayConfig;
import com.alipay.config.ZhifuConfig;

public class PayServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	
	private static Logger logger=Logger.getLogger(PayServlet.class.getName());
	
	private static boolean isInit=false;
	
	public void init(ServletConfig servletConfig) throws ServletException {
		ParseConfig.execute();//解析XML配置
		super.init();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String url=request.getRequestURL().toString();
		logger.debug(url);
		
		if(!isInit){
			String projectUrl=url.substring(0,url.lastIndexOf("/"));
			
			//初始化支付宝的配置
			AlipayConfig.init(projectUrl);
			
			//初始化智付的配置
			ZhifuConfig.init(projectUrl);
			
			isInit=true;
		}
		
		ExtendMap<String,Object> paramMap=getParameterMap(request);
		String requestInfo=url.substring(0,url.lastIndexOf("."));
		
		if(requestInfo.contains("submit")){//提交支付请求
			PayService.submit(paramMap,request,response);
		}else if(requestInfo.contains("aliTbNotify")){//支付宝同步通知
			PayService.aliTbNotify(paramMap,request,response);
		}else if(requestInfo.contains("aliYbNotify")){//支付宝异步通知
			PayService.aliYbNotify(paramMap,request,response);
		}else if(requestInfo.contains("zhifuTbNotify")){//智付同步通知
			PayService.zhifuTbNotify(paramMap,request,response);
		}else if(requestInfo.contains("zhifuYbNotify")){//智付异步通知
			PayService.zhifuYbNotify(paramMap,request,response);
		}else if(requestInfo.contains("weixinAppOrder")){//微信统一下单
			WeixinService.weixinAppOrder(paramMap,request.getRequestURL().toString(),request.getRemoteAddr(),response);
		}else if(requestInfo.contains("weixinYbNotify")){//微信异步通知 //微信现在暂时没有同步通知
			WeixinService.weixinYbNotify(request,response);
		}

		else{
			throw new ServletException("无效的请求！");
		}
	}
	
	private ExtendMap<String,Object> getParameterMap(HttpServletRequest request){
		ExtendMap<String,Object> map=new ExtendMap<String,Object>();
		
		try{
			//设入普通参数
			Map<String,String[]> paramMap=request.getParameterMap();
			Iterator<String> iter=paramMap.keySet().iterator();
			while(iter.hasNext()){
				String name=iter.next();
				String values[]=paramMap.get(name);
				for(int i=0;i<values.length;i++){
					if(StringUtil.isMessyCode(values[i])){
//						System.out.println("乱码处理："+name+"，值："+values[i]);
						values[i]=new String(values[i].getBytes("ISO-8859-1"),"UTF-8") ;
					}
				}
				map.put(name,values.length>1 ? values : values[0]);
			}
			
			//设入Attribute
			Enumeration<String> enumeraction=request.getAttributeNames();
			while(enumeraction.hasMoreElements()){
				String name=enumeraction.nextElement();
				map.put(name,request.getAttribute(name));
			}
			
			logger.debug(map);
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		
		return map;
	}
}